package com.kingint.web.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingint.mbg.dto.UmsAdminLoginParam;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.mbg.sys.entity.UmsMemberRoleRelation;
import com.kingint.mbg.sys.entity.UmsPermission;
import com.kingint.mbg.sys.entity.UmsRole;
import com.kingint.mbg.sys.mapper.UmsMemberMapper;
import com.kingint.mbg.sys.mapper.UmsMemberRoleRelationMapper;
import com.kingint.web.domain.MemberDetails;
import com.kingint.web.sys.service.UmsAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingint.web.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2020-09-18
 */
@Service
@Slf4j
public class UmsAdminServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements UmsAdminService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private UmsMemberMapper adminMapper;
    @Resource
    private UmsMemberRoleRelationMapper adminRoleRelationMapper;

    @Override
    public String login(UmsAdminLoginParam umsAdminLoginParam) {

        String username = umsAdminLoginParam.getUsername();
        String password = umsAdminLoginParam.getPassword();
        String token = null;
        //创建UsernamePasswordAuthenticationToken,这是Authentication的实现类，传入用户名和密码做构造参数，这个对象就是我们创建出来的未认证的Authentication对象。
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
        try {
            //认证 authenticationManager调用它的authenticate方法进行认证，返回一个认证完成的Authentication对象。
            Authentication authentication = authenticationManager.authenticate(authenticationToken);

            //认证成功后保存认证信息 将authentication放入 通过springcontexthoder中getContext方法获取的securityContext的上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            //方式一：通过username获取到会员对象信息
            UmsMember adminByName = getAdminByName(username);

            //方式二：从Authentication对象中拿到我们的UserDetails对象，认证后的Authentication对象调用它的getPrincipal()方法就可以拿到我们先前数据库查询后组装出来的UserDetails对象
//            UserDetail userDetail = (UserDetail) authentication.getPrincipal();

            UserDetails userDetails = new MemberDetails(adminByName);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String oldToken) {
        String token = oldToken.substring(tokenHead.length());
        if (jwtTokenUtil.canRefresh(token)) {
            return jwtTokenUtil.refreshToken(token);
        }
        return null;
    }

    @Override
    public UmsMember getAdminByName(String username) {
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username)
                .eq("account_status",0);
        List<UmsMember> umsAdmins = adminMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(umsAdmins)){
            return umsAdmins.get(0);
        }
        return null;
    }

    @Override
    public int delete(Long id) {
        int i = adminMapper.deleteById(id);
        //同时删除用户与角色表
        QueryWrapper<UmsMemberRoleRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_id",id);
        adminRoleRelationMapper.delete(wrapper);
        return i;
    }

    @Override
    public List<UmsRole> getRoleList(Long adminId) {
        List<UmsRole> roleList = adminRoleRelationMapper.getRoleList(adminId);
        return roleList;
    }

    @Override
    public UmsMember getCurrentMember() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            return memberDetails.getUmsMember();
        } catch (Exception e) {
            return new UmsMember();
        }
    }

    @Override
    public UmsMember getCurrentMember1() {
        UmsMember umsMember = adminMapper.selectById(2);
        return umsMember;
    }

    @Override
    public List<UmsPermission> getPermissionList(Long id) {
        List<UmsPermission> rolePermissionList = adminRoleRelationMapper.getRolePermissionList(id);
        return rolePermissionList;
    }

    @Override
    public UmsMember getByPhone(String username) {
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",username)
                .eq("account_status",0);
        UmsMember umsMember = adminMapper.selectOne(wrapper);
        return umsMember;
    }
}
